<template>
    <div class="my-info-container">
        <div class="user-info-container">
            <div class="info">
                <el-form ref="form" :model="form" :rules="rules" label-width="120px">

                    <el-form-item label="用户姓名：" prop="realName">
                        <el-input v-model="form.realName" style="width: 306px;"></el-input>
                    </el-form-item>

                    <el-form-item label="邮箱地址：" prop="email">
                        <el-input v-model="form.email" style="width: 306px;"></el-input>
                    </el-form-item>

                    <el-form-item label="手机号码：" prop="mobile">
                        <el-input v-model="form.mobile" style="width: 306px;"></el-input>
                    </el-form-item>

                    <el-form-item label="登录账号：">
                        <el-input v-model="user.account" disabled style="width: 306px;"></el-input>
                    </el-form-item>

                    <el-form-item label="登录密码：">
                        <el-button type="text" @click="dialogEditPassVisible = true">修改密码</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div class="avatar">
                <div class="my-avatar">
                    <img :src="userAvatar" alt="">
                    <file-upload
                            class="btn el-button el-button--text"
                            :multiple="false"
                            :drop="true"
                            :drop-directory="true"
                            :post-action="uploadUrl"
                            v-model="files"
                            @input-filter="inputFilter"
                            @input-file="inputFile"
                            ref="upload">
                        选择图片
                    </file-upload>
                </div>

                <div class="preview" v-show="previewImg">
                    <img :src="previewImg"  alt="图片预览">
                    <template v-if="files.length > 0">
                        <el-button class="upload-btn" icon="el-icon-upload" type="text" v-if="!files[0].success && files[0].active == false"
                                   :disabled="(!$refs.upload || !$refs.upload.active ? false : true)"
                                   @click.prevent="$refs.upload.active = true">上传头像</el-button>

                            <div style="text-align: center;margin-top: 10px;">
                                <span v-if="files[0].error" style="color: #FA5555">{{files[0].error}}</span>
                                <span v-else-if="files[0].success" style="color: #67C23A">上传成功，请保存</span>
                                <span v-else-if="files[0].active" style="color: #409EFF">上传中</span>
                                <span v-else></span>
                            </div>
                    </template>
                </div>
            </div>
        </div>
        <div class="user-info-bto">
            <el-button>取消</el-button>
            <el-button type="primary" @click="updateInfo">保存</el-button>
        </div>

        <el-dialog title="修改密码" :visible.sync="dialogEditPassVisible" :close-on-press-escape="false" :close-on-click-modal="false"  @close="resetEditPasswordForm">
            <el-form :model="editPasswordForm" :rules="editPasswordRules" ref="editPasswordForm" labelPosition="right" labelWidth="100px" style="width: 400px">
                <el-form-item label="原密码" prop="oldPassword">
                    <el-input v-model="editPasswordForm.oldPassword"></el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                    <el-input v-model="editPasswordForm.newPassword"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="rePass">
                    <el-input v-model="editPasswordForm.rePass"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogEditPassVisible = false">取 消</el-button>
                <el-button type="primary" @click="updatePassword">确 定</el-button>
            </div>
        </el-dialog>

    </div>

</template>

<script>
    import FileUpload from 'vue-upload-component'
    import ImageCompressor from 'image-compressor'
    import { mapGetters } from 'vuex'
    import { updatedMyInfo, updateMyPassword, updateMyAvatar, uploadUrl } from '@/api/system/user'
    import { getToken } from "@/libs/auth";
    import uAvatar from '@/assets/images/avatar/avatar1.jpeg'
    export default {
        name: "my-info",
        components: {
            FileUpload
        },
        computed: {
            ...mapGetters(['user', 'roles', 'page_permissions', 'action_permissions'])
        },
        created() {

            this.form.id = this.user.id
            this.form.realName = this.user.realName
            this.form.email = this.user.email
            this.form.mobile = this.user.mobile
            this.form.avatar = this.user.avatar
            this.editPasswordForm.id = this.user.id

            if(this.form.avatar) {
                this.userAvatar = this.form.avatar
            } else {
                this.userAvatar = uAvatar
            }
        },
        mounted: function () {
            this.$nextTick(function () {
            })
        },
        data() {
            const validPhone = (rule, value, callback) => {
                var re = /^1[0-9]{10}$/;
                if (!re.test(value)) {
                    callback(new Error('请输入正确格式的手机号'));
                } else {
                    callback();
                }
            }
            const validRePassword = (rule, value, callback) => {
                if (value !== this.editPasswordForm.newPassword) {
                    callback(new Error('两次输入密码不一致'));
                } else {
                    callback();
                }
            }
            return {
                form: {},
                rules: {
                    realName: [
                        { required: true, message: '请输入姓名', trigger: 'blur' }
                    ],
                    email: [
                        { required: true, message: '邮件地址不能为空', trigger: 'blur' },
                        { type: 'email', message: '邮件格式不正确', trigger: 'blur' }
                    ],
                    mobile: [
                        { required: true, message: '请输入手机号码' },
                        { validator: validPhone }
                    ]
                },
                dialogEditPassVisible: false, // 修改密码Dialog
                editPasswordForm: {
                    oldPassword: '',
                    newPassword: '',
                    rePass: ''
                },
                editPasswordRules: {
                    oldPassword: [
                        { required: true, message: '请输入原密码', trigger: 'blur' }
                    ],
                    newPassword: [
                        { required: true, message: '请输入新密码', trigger: 'blur' },
                        { min: 6, message: '请至少输入6个字符', trigger: 'blur' },
                        { max: 32, message: '最多输入32个字符', trigger: 'blur' }
                    ],
                    rePass: [
                        { required: true, message: '请再次输入新密码', trigger: 'blur' },
                        { validator: validRePassword, trigger: 'blur' }
                    ]
                },

                uploadLoading: false,
                userAvatar: null,

                previewImg: null,
                files: [],
                uploadUrl: uploadUrl,
                uploadAuto: false,
                autoCompress: 1024 * 1024 * 2,
                size: 1024 * 1024 * 2,
            }
        },
        methods: {
            updateInfo() {  //修改信息
                this.$refs['form'].validate((valid) => {
                    if (valid) {
                        let self = this
                        updatedMyInfo(this.form).then(response => {
                            if (response.data.status === 200) {
                                this.$store.dispatch('FedLogOut').then(() => {
                                    this.$alert('修改成功，请重新登录', '提示', {
                                        confirmButtonText: '重新登陆',
                                        callback: () => {
                                            this.$loading({
                                                lock: true,
                                                text: '正在退出，请稍等...',
                                                background: 'rgba(0, 0, 0, 0.7)'
                                            });
                                            setTimeout(()=>{
                                                window.location.reload()
                                            }, 500)

                                        }
                                    })
                                })
                            } else if(response.data.status === 601) {
                                this.$notify({
                                    title: '提示', message: response.data.msg,
                                    type: 'warning', duration: 2000
                                })
                            } else {
                                this.$notify({
                                    title: '发生错误', message: response.data.msg,
                                    type: 'error', duration: 2000
                                })
                            }
                        }).catch(error => {})
                    }
                })
            },
            updatePassword() { //修改密码
                this.$refs['editPasswordForm'].validate((valid) => {
                    if (valid) {
                        updateMyPassword(this.editPasswordForm).then(response => {
                            if (response.data.status === 200) {
                                this.dialogEditPassVisible = false
                                this.$notify({
                                    title: '提示', message: '操作成功',
                                    type: 'success', duration: 2000
                                })
                            } else if(response.data.status === 601) {
                                this.$notify({
                                    title: '提示', message: response.data.msg,
                                    type: 'warning', duration: 2000
                                })
                            } else {
                                this.$notify({
                                    title: '发生错误', message: response.data.msg,
                                    type: 'error', duration: 2000
                                })
                            }
                        }).catch(error => {})
                    }
                })
            },
            changeAvatar(data) { //修改头像
                return updateMyAvatar(data).then(response => {
                    return response
                })
            },
            resetEditPasswordForm() {
                this.$refs['editPasswordForm'].resetFields()
                this.editPasswordForm = {
                    id:this.user.id,
                    oldPassword: '',
                    newPassword: '',
                    rePass: ''
                }
            },
            inputFilter(newFile, oldFile, prevent) {
                if (newFile && !oldFile) {
                    // 添加文件前
                    // 过滤系统文件 和隐藏文件
                    if (/(\/|^)(Thumbs\.db|desktop\.ini|\..+)$/.test(newFile.name)) {
                        return prevent()
                    }
                    // 过滤 php html js 文件
                    if (/\.(php5?|html?|jsx?)$/i.test(newFile.name)) {
                        return prevent()
                    }

                    // 自动压缩
                    if (newFile.file && newFile.type.substr(0, 6) === 'image/' && this.autoCompress > 0 && this.autoCompress < newFile.size) {
                        newFile.error = 'compressing'
                        const imageCompressor = new ImageCompressor(null, {
                            convertSize: Infinity,
                            maxWidth: 512,
                            maxHeight: 512,
                        })
                        imageCompressor.compress(newFile.file)
                            .then((file) => {
                                this.$refs.upload.update(newFile, { error: '', file, size: file.size, type: file.type })
                            })
                            .catch((err) => {
                                this.$refs.upload.update(newFile, { error: err.message || 'compress' })
                            })
                    }

                    if (newFile && (!oldFile || newFile.file !== oldFile.file)) {
                        // 创建 blob 字段
                        newFile.blob = ''
                        let URL = window.URL || window.webkitURL
                        if (URL && URL.createObjectURL) {
                            newFile.blob = URL.createObjectURL(newFile.file)
                        }
                        // 缩略图
                        newFile.thumb = ''
                        if (newFile.blob && newFile.type.substr(0, 6) === 'image/') {
                            newFile.thumb = newFile.blob
                            this.previewImg = newFile.thumb
                        }
                    }
                }
            },
            inputFile(newFile, oldFile) {
                let self = this
                if (newFile && !oldFile) {
                    // 添加文件
                }

                if (newFile && oldFile) {
                    // 更新文件

                    // 开始上传
                    if (newFile.active && !oldFile.active) {
                        // beforeSend
                        /*this.uploadLoading = this.$loading({
                            lock: true,
                            text: '头像上传中',
                            spinner: 'el-icon-loading',
                            background: 'rgba(0, 0, 0, 0.7)'
                        });*/
                        //设置每个文件携带的参数
                        newFile.data = Object.assign({}, {
                            'ossName': 'qiniuyun',
                            'bucketName': 'test',   //空间名称
                            'prefixName': 'avatar'
                        })
                        newFile.headers = {
                            'Auth-Token': getToken()
                        }
                        // 限定最小字节
                        if (newFile.size >= 0 && this.minSize > 0 && newFile.size < this.minSize) {
                            this.$refs.upload.update(newFile, { error: 'size' })
                        }
                    }
                    // 上传进度
                    if (newFile.progress !== oldFile.progress) {
                        //console.log('progress', newFile.progress, newFile)
                    }
                    // 上传错误
                    if (newFile.error !== oldFile.error) {
                        //console.log('error', newFile.error, newFile)
                        //this.uploadLoading.close();
                    }
                    // 上传成功
                    if (newFile.success !== oldFile.success) {
                        const response = newFile.response ;

                        if (response.status === 200) {
                            this.form.avatar = response.data.url
                            self.userAvatar = newFile.blob

                        } else if (response.status === 601) {
                            this.uploadLoading.close();
                            this.$notify({
                                title: '提示', message: response.msg,
                                type: 'warning', duration: 2000
                            })
                        } else {
                            this.uploadLoading.close();
                            this.$notify({
                                title: '操作失败', message: response.msg,
                                type: 'error', duration: 2000
                            })
                        }
                    }
                }

                if (!newFile && oldFile) {
                    // 删除文件
                    // 自动删除 服务器上的文件
                    if (oldFile.success && oldFile.response.id) {
                        // $.ajax({
                        //   type: 'DELETE',
                        //   url: '/file/delete?id=' + oldFile.response.id,
                        // });
                    }
                }

                // 自动上传
                if (Boolean(newFile) !== Boolean(oldFile) || oldFile.error !== newFile.error) {
                    if (this.uploadAuto && !this.$refs.upload.active) {
                        this.$refs.upload.active = true

                    }
                }
            }

        }
    }
</script>

<!-- 局部样式 -->
<style rel="stylesheet/scss" lang="scss" scoped>

    .my-info-container{
        .user-info-container{
            display: flex;
            flex-direction: row;

            .info{
                margin-right: 100px;
            }
            .avatar {
                display: flex;
                flex-direction: row;

                .my-avatar{
                    display: flex;
                    flex-direction: column;
                    height: 150px;
                    width: 150px;
                    img{
                        width: 100%;
                        height: 100%;
                        min-height: 150px;
                        min-width: 150px;
                        border-radius: 50%;
                    }
                    label.btn {
                        padding-bottom: 25px;
                    }
                }

                .preview{
                    display: flex;
                    flex-direction: column;
                    height: 150px;
                    width: 150px;
                    margin-left: 10px;
                    img{
                        width: 100%;
                        height: 100%;
                        min-height: 150px;
                        min-width: 150px;
                        border-radius: 50%;
                    }
                    .upload-btn{
                        align-self: center;
                    }
                }

            }
        }
        .user-info-bto{
            margin-left: 35px;
        }
    }

</style>
